$(function (){
	
	var video = document.querySelector('video');
var text = document.getElementById('text');
var canvas1 = document.getElementById('qr-canvas');
var context1 = canvas1.getContext('2d');
var mediaStreamTrack;
var i = 0;
// 一堆兼容代码
window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
if(navigator.mediaDevices === undefined) {
	navigator.mediaDevices = {};
}
if(navigator.mediaDevices.getUserMedia === undefined) {
	navigator.mediaDevices.getUserMedia = function(constraints) {
		var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
		if(!getUserMedia) {
			return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
		}
		return new Promise(function(resolve, reject) {
			getUserMedia.call(navigator, constraints, resolve, reject);
		});
	}
}

//摄像头调用配置
var mediaOpts = {
	audio: true,
	video: true,
	video: {
		facingMode: "environment"
	} // 或者 "user"
	// video: { width: 1280, height: 720 }
	// video: { facingMode: { exact: "environment" } }// 或者 "user"
}
var zxaf = "";
// 回调
function successFunc(stream) {
	mediaStreamTrack = stream;
	video = document.querySelector('video');
	if("srcObject" in video) {
		video.srcObject = stream
	} else {
		video.src = window.URL && window.URL.createObjectURL(stream) || stream
	}
	video.play();
	drawMedia();
	zxaf = setInterval(drawMedia, 2000);
}

function errorFunc(err) {
	alert("你换个浏览器试哈子！火狐，IE啥的都行！");
}

// 正式启动摄像头
function openMedia() {
	navigator.mediaDevices.getUserMedia(mediaOpts).then(successFunc).catch(
		errorFunc
	);
}

//关闭摄像头
function closeMedia() {
	i = 0;
	mediaStreamTrack.getVideoTracks().forEach(function(track) {
		track.stop();
		context1.clearRect(0, 0, context1.width, context1.height); //清除画布
	});
}

navigator.mediaDevices.getUserMedia(mediaOpts).then(successFunc).catch(errorFunc);
//	setTimeout(drawMedia(),30000);
//setTimeout(drawMedia, 3000);
//setTimeout(closeMedia,5000);

$("#openc").on('click' ,function (){
	debugger;
	openMedia();
	$(".jg").show();
})
//截取视频
function drawMedia() {
	console.log("ks");
	i++;
	if(i > 3) {
		window.clearTimeout(zxaf);
		closeMedia();
	}
	canvas1.setAttribute("width", video.videoWidth);
	canvas1.setAttribute("height", video.videoHeight);
	context1.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
	image = canvas1.toDataURL('image/png');
	var img = new Image();
	//设置属性和src
	img.id = "newImg";
	img.src = image;
	img.onload = function() {
		var a = document.getElementById('video');
		a.appendChild(img)
		a.href = image;
		a.download = 'aaa'; // 下载的图片的名称
		var formData = new FormData();
		var blo = convertBase64UrlToBlob(a.href);
		formData.append("file", blo);
		formData.append("tpid", createguid());
		formData.append("asdasd", "Asda");
		$.ajax({
			url: "../../te/loadtx",
			type: "post",
			contentType: false,
			processData: false,
			dataType: 'json',
			data: formData,
			success: function(d) {
				console.log(d);
			}
		})
	}
}

function S4() {
	return(((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function createguid() {
	return(S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function convertBase64UrlToBlob(base64) {
	var type = base64.split(",")[0].match(/:(.*?);/)[1]; //提取base64头的type如 'image/png'     
	var bytes = window.atob(base64.split(',')[1]); //去掉url的头，并转换为byte (atob:编码 btoa:解码)

	//处理异常,将ascii码小于0的转换为大于0 
	var ab = new ArrayBuffer(bytes.length); //通用的、固定长度(bytes.length)的原始二进制数据缓冲区对象
	var ia = new Uint8Array(ab);
	for(var i = 0; i < bytes.length; i++) {
		ia[i] = bytes.charCodeAt(i);
	}
	return new Blob([ab], {
		type: type
	});
}
})
